/*
 * File: MidpointFindingKarel.java
 * -------------------------------
 * When you finish writing it, the MidpointFindingKarel class should
 * leave a beeper on the corner closest to the center of 1st Street
 * (or either of the two central corners if 1st Street has an even 
 * looks for the midpoint, but must pick them up again before it
 * stops.  The world may be of any size, but you are allowed to
 * assume that it is at least as tall as it is wide.
 */

import stanford.karel.*;

public class MidpointFindingKarel extends SuperKarel {
	
	/* Find the middle point of 1st Ave using beepers only */ 
	public void run() {
		/* put a full row of beepers */
		putRowOfBeepers();
		
		/* iterate picking beepers from both ends of the row */ 
		while(beepersPresent()){		
			/* pick the beeper from the end of the row */
			pickBeeper();
			/* go to the other end */
			moveToEndOfRow();
			/* leave Karel facing the opposite side to start again */
			turnAround();
			/* move to next starting position, the beginning of the row */
			if (frontIsClear()){
				move();
			}
		}
		
		/* put a beeper in the center */
		putBeeper();
	}
	
	/* Moves Karel to the end of the row 
	 * Precondition: Karel is facing to the opposite end of the row over an 
	 * empty cell
	 * Postcondition: Karel is positioned in the end of the opposite row. 
	 * If Karel hits the wall, it will pick the beeper and leave the cell empty.
	 */
	private void moveToEndOfRow(){
		/* position Karel over the next beeper as a starting point */
		if (frontIsClear()){
			move();
		}
		
		/* move Karel until the end of the row */
		while(beepersPresent()){
			if (frontIsClear()){
				move();
			}
			
			/* Karel might not be able to continue moving
			 * so the end of the row was reached. In this case
			 * we check if there are any beepers to remove.
			 */
			if (frontIsBlocked()){
				if (beepersPresent()){
					pickBeeper();
				}
			}
		}
	}
	
	/*
	 *  Karel puts a beeper in each cell of the 1st Av. 
	 */
	private void putRowOfBeepers(){
		putBeeper();
		while(frontIsClear()){
			move();
			putBeeper();
		}
		turnAround();
	}
}
